<template>
    <view>
        <cu-custom bgColor="bgmain" :isBack="true">
            <view slot="content">商品列表</view>
        </cu-custom>
        <view class="shore_info padding row">
            <image class="main_img margin-right"
                :src="store.business_image||'https://www.xiaoaojianghu.top/wximage/empty.jpg'" mode="scaleToFill" />


            <view class="flex" style="height: 148rpx;" v-if="store.business_id">
                <view class="name" @click="call(store.phone)">{{store.business_name}}
                    <text style="color:#ff6344;" class="cuIcon-phone margin-left-xs"></text>
                </view>
                <view class="time row">营业时间：
                    {{store.timeslot}}

                    <!-- {{store.start_time}}~{{store.end_time}} -->
                    <view class="margin-left">销量：{{store.sale_num}}</view>
                </view>
                <view class="tags row">
                    <view class="tag">起送￥{{starting_fee}}</view>
                   
                    <view class="tag" v-if=" store.is_dormitory_store==1">宿舍小店</view>
                    <view class="tag" v-else>{{store.type==1?"校内":"校外"}}</view>
                </view>

            </view>
        </view>
        <view class="store-container">
            <view class="food">
                <view class="food-class" :style="'height:' + listHeight + 'px'">
                    <scroll-view scroll-y scroll-with-animation :scroll-into-view="viewToLeft"
                        :style="'height:' + listHeight + 'px;padding-bottom:110rpx;'">
                        <view :class="'food-class-item ' + (activeIndex == index ? 'active' : '')" @tap="selectFood"
                            :data-index="index" :data-titleId="item.titleId" :id="item.titleId + 'left'"
                            v-for="(item, index) in food" :key="item.title">
                            <view class="text" :data-index="index" :data-titleId="item.titleId">{{ item.goods_type_name
                            }}</view>

                            <!-- <view class="dot" v-if="item.foodCount > 0">{{ item.foodCount }}</view> -->
                        </view>
                    </scroll-view>
                </view>
                <view class="food-detail">
                    <scroll-view scroll-y scroll-with-animation
                        :style="'height:' + listHeight + 'px;padding-bottom:110rpx;'" :scroll-into-view="viewTo"
                        @scroll="scroll">
                        <view class="title-group" v-for="(Pitem, groupindex) in food" :key="item.name">
                            <view class="title" :id="Pitem.titleId">{{ Pitem.goods_type_name }}</view>

                            <view class="food-info" v-for="(item, index) in Pitem.items" :key="Pitem.goodId">
                                <view class="end" v-if="item.stock==0"> 已售空</view>

                                <view class="img">
                                    <image :src="item.goods_img" @tap="preview" :data-url="item.goods_img"></image>
                                    <!-- <image src='/images/store.png'></image> -->
                                </view>

                                <view class="info">
                                    <view class="name">{{ item.goods_name }}</view>
                                    <view class="stock">库存：{{item.stock}}</view>
                                    <view class="price-count">
                                        <view class="price">￥{{ item.price }}</view>
                                        <block v-if="item.stock>0">
                                            <view class="count row" v-if="!item.attribute&&!item.specs">
                                                <!-- <view class="add btns" @tap="add" :data-item="item" :data-groupindex="groupindex" :data-index="index">+</view> -->
                                                <view style="width:76rpx;">
                                                    <image class="jia" @tap="add" :data-item="item"
                                                        :data-groupindex="groupindex" :data-index="index"
                                                        src="/static/icon/shop/jia.png" mode="scaleToFill" 
                                                        v-if="!item.quota||(item.quota&&item.count<item.quota)"
                                                        />
                                                </view>

                                                <view class="num">{{ item.count }}</view>
                                                <!-- <view
                                                    class="ruduce btns"
                                                    @tap="reduce"
                                                    :data-item="item"
                                                    v-if="item.count > 0 ? true : false"
                                                    :data-groupindex="groupindex"
                                                    :data-index="index"
                                                >
                                                    -
                                                </view> -->
                                                <image class="jian" @tap="reduce" src="/static/icon/shop/jian.png"
                                                    mode="scaleToFill" :data-item="item"
                                                    v-if="item.count > 0 ? true : false" :data-groupindex="groupindex"
                                                    :data-index="index" />
                                            </view>
                                            <view  v-else>
                                                <!-- {{item.id}}
                                                {{cart.filter(i=>i.id==item.id)}} -->
                                                <!-- {{getNums(item.id)}} -->
                                                    <view v-if="cart.length>0&&cart.filter(i=>i.id==item.id).length>0">

                                                        <view class=" changeSpecs" @click="showSpecs" :data-item="item"
                                                            v-if="!item.quota||(item.quota&&item.quota>cart.filter(i=>i.id==item.id).map(i=>i.count).reduce((n,m) => n + m))"
                                                        >选规格
                                                        </view>
                                                    </view>
                                                    <view v-else>
                                                        <view class=" changeSpecs" @click="showSpecs" :data-item="item">选规格
                                                        </view>
                                                    </view>
                                            </view>

                                        </block>

                                    </view>
                                </view>
                            </view>
                        </view>
                        <view class="notData" v-if="food.length==0">
                            <image class="icon" src="/static/icon/notDatas.png" mode="widthFix" />
                            暂无商品
                        </view>
                        <!-- <view wx:for="{{food}}" wx:key="item.name" class="title-group" wx:for-index="groupindex">
          <view class='title' id='{{item.titleId}}'>{{item.name}}</view>
          <view wx:for="{{item.items}}" wx:key="item.goodId" class='food-info' wx:for-index="index">
            <view class='img'>
              <image src='{{item.img}}' bindtap="preview" data-url="{{item.img}}"></image>
            </view>
            <view class='info'>
              <view class='name'>{{item.name}}</view>
              <view class='price-count'>
                <view class='price'>￥{{item.price}}</view>
                <view class='count'>
                  <view class='add btns' bindtap="add" data-item="{{item}}" data-groupindex="{{groupindex}}" data-index="{{index}}">+</view>
                  <view class='num'>{{item.count}}</view>
                  <view class='ruduce btns' bindtap="reduce" data-item="{{item}}" wx:if="{{item.count>0?true:false}}"
                    data-groupindex="{{groupindex}}" data-index="{{index}}">-</view>
                </view>
              </view>
            </view>
          </view>
        </view> -->
                    </scroll-view>
                </view>
            </view>
            <view class="cart">
                <view class="cart-container">
                    <view :class="'cart-img ' + (cart.length > 0 ? 'has-food' : '')" @tap="listCart">
                        <image
                            :src="cart.length > 0 ? '/static/images/gouwuche-black.png' : '/static/images/gouwuche.png'">
                        </image>
                    </view>
                    <view class="del-price-money">
                        <view class="money">￥{{ totalMoney }}</view>
                    </view>
                    <view v-if="status == 2 || time_status == 0" class="start-del end">已打烊</view>
                    <!-- parseEventDynamicCode -->
                    <view v-else @click="check"
                        :class="'start-del ' + (totalMoney >= starting_fee && cart.length > 0 ? 'has-food' : '')">
                        {{ totalMoney >= starting_fee && cart.length > 0 ? '去结算' : '起送费'+starting_fee }}
                    </view>
                </view>
                <view class="cart-list" v-if="showCart==123">
                    <view class="cart-list-header" @tap="listCart">关闭</view>
                    <view class="cart-list-item">
                        <view class="item" v-for="(item, index) in cart" :key="index">
                            <view class="cart-detail">{{ item.goods_name }}</view>

                            <view class="cart-detail" style="color: red">￥{{ item.price }}</view>

                            <view class="cart-detail cart-count">
                                <view class="add btns" @tap="reduce" :data-id="item.id"
                                    :data-groupindex="item.groupindex" :data-index="item.index">-</view>
                                {{ item.count }}
                                <view class="add btns" @tap="add" :data-id="item.id" :data-groupindex="item.groupindex"
                                    :data-index="item.index">+</view>
                            </view>
                        </view>
                    </view>
                </view>
            </view>
        </view>
        <view class="new_cart padding-lr-xl row">
            <image class="icon margin-right" src="/static/icon/shop/car.png" mode="scaleToFill" @tap="listCart" />
            合计：<view class="price row">￥
                <view class="f40">{{totalMoney}}</view>
            </view>
            <!-- <view v-if="status == 2 || time_status == 0" class="buy" style="background-color: gray;">已打烊</view> -->
            <view v-if="store.is_open == 0" class="buy" style="background-color: gray;">已打烊</view>

            
            <view class="buy" @click="check" v-else>
                {{ 
                    Number(totalMoney) < Number(starting_fee)
                    ? ('起送费'+starting_fee ):'确认购买'
                }}
                <!-- {{getTips()}} -->
            </view>
        </view>
        <view class="cu-modal bottom-modal specs_modal" :class="modalName=='specs'?'show':''" @tap="hideModal">
            <view class="cu-dialog" @tap.stop="" v-if="curItem.id">
                <!-- <view class="cu-bar bg-white">
					<view class="action text-blue" @tap="hideModal">取消</view>
					<view class="action text-green" @tap="hideModal">确定</view>
				</view> -->
                <view class="padding">
                    <view class="goods_info row">
                        <image class="goods_img" :src="curItem.goods_img" mode="scaleToFill" />
                        <view class="main">
                            <view class="name row">{{curItem.goods_name}}</view>
                            <view class="price row">￥{{ (curItem.price*1+specssPrice*1).toFixed(2)}}
                                <!-- <block v-if="specssPrice>0">
                                   (+{{specssPrice}}元)
                                </block> -->
                            </view>
                        </view>
                        <view class="cuIcon-close" @click="hideModal"></view>
                    </view>
                    <view class="sku_box">
                        <view class="flex-col  margin-top">
                            <view class="key row">{{curItem.specs.name}}</view>
                            <view class="tags row margin-top-sm">
                                <block v-for="(item,index) in curItem.specs.list" :key="index">
                                    <view class="tag margin-right margin-bottom-sm"
                                        :class="curItem.changeSpecs==item.type?'cur':''" @click="changeSpecs(item)">
                                        {{item.type}}
                                        ￥{{item.price}}
                                    </view>
                                </block>
                            </view>
                        </view>
                        <!-- <view v-if="1==1">
                            <view class="key row">{{curItem.attribute.name}}</view>
                            <view class="tags row margin-top-sm" v-if="curItem.attribute.list">
                                <block v-for="(item,index) in curItem.attribute.list" :key="index">
                                    <view class="tag  margin-right margin-bottom-sm"
                                        :class="curItem.changeAttribute.includes(item)?'cur':''"
                                        @click="changeAttribute(item)">
                                        {{item}}
                                    </view>
                                </block>
                            </view>
                        </view> -->
                        <block v-for="(Pitem,Pindex) in curItem.specs_list" :key="Pindex">
                            <view class="flex-col  margin-top dgg">
                                <view class="key row">{{Pitem.name}}</view>
                                <view class="tags row margin-top-sm">
                                    <block v-for="(item,index) in Pitem.list" :key="index">
                                        <view class="tag margin-right margin-bottom-sm row" :style="item.price>0?'':'padding-right:20rpx;'" :class="specss[Pindex].type==item.type?'cur':''"
                                            @click="changeSpecss(item,Pindex)">
                                            {{item.type}}
                                            <view class="price" v-if="item.price>0">
                                                ￥{{item.price}}
                                            </view>
                                            <!-- {{item.price}} -->
                                        </view>
                                    </block>
                                </view>
                            </view>
                        </block>
                        <view class="row margin-tb-sm">
                            <view class="key">数量</view>
                            <view class="nums row" style="margin-left:auto;">
                                <image class="jian" src="/static/icon/shop/jian.png" mode="scaleToFill"
                                    v-if="curItem.count>1" @tap="new_jian" :data-id="curItem.id"
                                    :data-groupindex="curItem.groupindex" :data-index="curItem.index"
                                    :data-items="curItem" />
                                <view class="num">{{ curItem.count }}</view>
                                <!-- /{{curItem.quota}}/{{curItem.count}} -->
                                <view style="width:76rpx;">
                                <view v-if="cart.length>0&&cart.filter(i=>i.id==curItem.id).length>0">
                                    <image class="jia" @tap="new_jia" :data-id="curItem.id" :data-groupindex="curItem.groupindex"
                                        :data-index="curItem.index" :data-items="curItem"
                                        v-if="!curItem.quota||(curItem.quota&&(curItem.count+cart.filter(i=>i.id==curItem.id).map(i=>i.count).reduce((n,m) => n + m))<curItem.quota)"
                                        src="/static/icon/shop/jia.png" mode="scaleToFill" />
                                </view>
                                <view v-else>
                                    <image class="jia" @tap="new_jia" :data-id="curItem.id" :data-groupindex="curItem.groupindex"
                                        :data-index="curItem.index" :data-items="curItem"
                                        v-if="!curItem.quota||(curItem.quota&&(curItem.count)<curItem.quota)"

                                        src="/static/icon/shop/jia.png" mode="scaleToFill" />
                                    </view>
                                </view>
                            </view>
                        </view>
                    </view>


                    <view class="add margin-top" @click="addCar">加入购物车</view>
                </view>
            </view>
        </view>

        <view class="cu-modal bottom-modal car_modal" :class="showCart?'show':''" @tap="hideModal">
            <view class="cu-dialog padding" @tap.stop="">
                <!-- <view class="cu-bar bg-white">
					<view class="action text-blue" @tap="hideModal">取消</view>
					<view class="action text-green" @tap="hideModal">确定</view>
				</view> -->
                <view class="row">
                    已选商品
                    <view class="clear_all row" @click="clearAll">
                        <image class="icon margin-right-xs" src="/static/icon/shop/del.png" mode="scaleToFill" />
                        清空购物车
                    </view>
                </view>
                <view class="car_list margin-bottom-xl">
                    <block v-for="(item,index) in cart" :key="index">
                        <view class="car_item row margin-top">
                            <image class="main_img margin-right" :src="item.goods_img" mode="scaleToFill" />
                            <view class="main flex-col">
                                <view class="name row">{{item.goods_name}}</view>
                                <view class="spec row">
                                    {{item.changeSpecs||""}} {{item.changeAttribute||""}}
                                    <block v-if="item.specss">
                                        {{item.specss.map(i=>i.type).join(",")||""}}
                                    </block>
                                </view>
                                <view class="row">
                                    <view class="price">￥{{item.price}}</view>
                                    <view class="nums row">
                                        <image class="jian" src="/static/icon/shop/jian.png" mode="scaleToFill"
                                            @tap="new_jian" :data-id="item.id" :data-groupindex="item.groupindex"
                                            :data-index="item.index" :data-indexs="index" :data-items="item" />
                                        <view class="num">{{ item.count }}</view>
                                        <view style="width:76rpx;">
                                            <image class="jia" @tap="new_jia" :data-id="item.id"
                                                :data-groupindex="item.groupindex" :data-index="item.index"
                                                :data-indexs="index" :data-items="item" src="/static/icon/shop/jia.png"
                                                v-if="!item.quota||(item.quota&&item.count<item.quota)"
                                                mode="scaleToFill" />
                                        </view>
                                    </view>
                                </view>
                            </view>
                        </view>
                    </block>
                </view>
            </view>
        </view>
    </view>
</template>

<script>
// pages/store/store.js
var app = getApp();
// import aasxas from 'dcsdcds'
let timer;
export default {
    data() {
        return {
            viewTo: '',
            viewToLeft: '',
            listHeight: 650,
            activeIndex: 0,
            tabIndex: 0,
            showModal: false,
            showCart: false,
            heigthArr: [],
            cart: [],
            result: [],
            totalMoney: 0,
            food: '',
            status: '',
            time_status: '',
            groupindex: 0,
            starting_fee: 0,
            curItem: {},
            modalName: '',
            store: {},
            isBuy: false,
            specss:[],
            specssPrice:0
        };
    },
    onShareAppMessage: function () {
        // return {
        //   title: '自定义标题',
        //   path: '/page/user?id=123',
        // }
        const path = `/gc_school/pages/foold/foold?id=${this.store.business_id}&s_id=${this.store.s_id}`
        console.log(path);
        return {
            path
        }
    },
    
    // onShareTimeline: function () { },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        var that = this;
        uni.setStorageSync('store_id', options.id);
        if (options.s_id){
            uni.setStorageSync('schoolId', options.s_id);
        }
        // if (!uni.getStorageSync('schoolId')) {
        //     uni.reLaunch({ url: '/gc_school/pages/changeSchool/index' })
        //     return false
        // }
        app.globalData.util.request({
            url: 'ZhGoods/getBusinessGoods',
            method: 'GET',
            data: {
                business_id: options.id,
                type: 1,
                s_id: options.s_id||uni.getStorageSync('schoolId')
            },

            success(res) {
                console.log(res);
                that.setData({
                    food: res.data.data.goods,
                    status: res.data.data.status,
                    time_status: res.data.data.time_status,
                    starting_fee: res.data.data.starting_fee,
                    store: res.data.data.info,
                    // curItem:res.data.data.goods[1].items[0]
                });
                // that.showSpecs({
                //     currentTarget:{
                //         dataset:{
                //             item: res.data.data.goods[1].items[2]
                //         }
                //     }
                // })
            }
        }, true); // wx.setNavigationBarTitle({
        //   title: this.data.storeInfo.storeName
        // });

        // this.cart=JSON.parse(`
        // [{"id":42,"s_id":8,"wxapp_id":3,"goods_type_id":36,"business_id":63,"goods_name":"测试商品2","price":"100.00","goods_img":"https://image.mync.xyz/api/202204/202204201651120214241.png","specs":null,"attribute":null,"status":1,"createtime":1650444677,"sort":null,"count":1,"foodId":42,"groupindex":0,"index":0},{"id":41,"s_id":8,"wxapp_id":3,"goods_type_id":37,"business_id":63,"goods_name":"测试和是哪个品","price":"20","goods_img":"https://image.mync.xyz/api/202204/202204191814150213105.png","specs":{"name":"分量","list":[{"type":"小份","price":"15"},{"type":"中份","price":"18"},{"type":"大份","price":"20"}]},"attribute":{"name":"忌口","list":["不要香菜","无辣"]},"status":1,"createtime":1650363259,"sort":null,"count":0,"foodId":41,"changeSpecs":"大份","item":{"type":"大份","price":"20"},"changeAttribute":"无辣"}]
        // `)
        // this.showCart=true
    },
    watch: {
        totalMoney(val) {
            console.log(val);
            // this.isBuy = parseFloat(val) > parseFloat(this.starting_fee) ? true : false

            // if (() {
            // }else{
            //     this.isBuy=true
            // }
        }
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {
        let height1;
        let height2;
        let res = uni.getSystemInfoSync();
        let winHeight = res.windowHeight;
        let query = uni.createSelectorQuery();
        query.select('.cu-custom').boundingClientRect();
        console.log('这里', query.select('.cu-custom').boundingClientRect());
        this.setData({
            listHeight: winHeight - uni.getStorageSync('CustomBar') - 150 // listHeight: winHeight-170
            // listHeight: winHeight - height1 - height2
        }); // query.exec(res => {
        //   console.log("高度",res)
        //   height1 = res[0].height;
        //   let query1 = wx.createSelectorQuery();
        //   query1.select(".tab").boundingClientRect();
        //   query1.exec(res => {
        //     // height2 = res[0].height;
        //     this.setData({
        //       listHeight: winHeight-wx.getStorageSync('CustomBar')
        //       // listHeight: winHeight-170
        //       // listHeight: winHeight - height1 - height2
        //     });
        //     this.calculateHeight();
        //   });
        // });
    },
    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () { },
    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () { },
    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () { },
    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () { },
    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () { },
    /**
     * 用户点击右上角分享
     */
    // onShareAppMessage: function () {},
    methods: {
        changeSpecss(item={},Pindex=0){
            console.log(item);
            console.log(Pindex);

            if (this.specss[Pindex] && this.specss[Pindex].type==item.type) {
                this.specss[Pindex]=null
            } else {
                this.specss[Pindex]=item
            }
            this.$forceUpdate()
            this.specssPrice = this.specss.map(item=>item.price).reduce((pre,curr)=>{
                return pre*1+curr*1
            })

            console.log(this.specss);
        },
        getNums(id){
            let nums = this.cart.filter(i=>{
                return i.id == id
            })
            console.log(nums);
            return nums
        },
        getTips() {
            return (this.totalMoney >= this.starting_fee && this.cart.length > 0) ? '确认购买' : ('起送费' + this.starting_fee)

        },
        call(phoneNumber = "") {
            uni.makePhoneCall({
                phoneNumber
            });
        },
        clearAll() {
            this.cart = []
            this.showCart = false
            this.totalMoney = 0.00
            for (let i = 0; i < this.food.length; i++) {
                const element = this.food[i];
                for (let j = 0; j < element.items.length; j++) {
                    const item = element.items[j];
                    item.count = 0
                }

            }
            // this.hidden()
        },
        preview(e) {
            var tmp = [];
            tmp.push(e.target.dataset.url);
            var current = e.target.dataset.url;
            uni.previewImage({
                current: current,
                // 当前显示图片的http链接
                urls: tmp // 需要预览的图片http链接列表
            });
        },
        addCar() {
            let item = JSON.stringify(this.curItem)
            item = JSON.parse(item)

            item.specssPrice = this.specssPrice
            item.specss = this.specss
            
           
            try {
                item.price = this.specssPrice*1 +item.item.price*1
                // item.price = item.price

                console.log(this.specssPrice + '+' + item.price);

            } catch (error) {
                try {
                    this.tips.tips("请选择" + item.specs.name)
                    return false
                } catch (error) {

                }

            }
            let cartItem = {}
            // let index
            // for (let i = 0; i < this.cart.length; i++) {
            //     const element = this.cart[i];
            //     if (element.changeAttribute.join(",")==item.changeAttribute.join(",")&&element.changeSpecs==item.changeSpecs) {
            //          cartItem=element
            //          index=i
            //     }
            // }
            if (cartItem.id) {
                console.log('购物车有');
                cartItem.count += item.count
                this.result[index].nums = cartItem.count

            } else {
                console.log('购物车无');
                this.cart = [
                    ...this.cart,
                    item
                ]
                this.result = [
                    ...this.result,
                    {
                        ids: item.foodId,
                        nums: item.count,
                        attribute: item.changeAttribute,
                        specs: item.changeSpecs
                    }
                ]

            }

            let totalMoney = parseFloat(this.totalMoney) + parseFloat(item.price * item.count);
            this.totalMoney = totalMoney.toFixed(2);
            this.hideModal()
        },
        hideModal() {
            this.modalName = ""
            this.showCart = false
            this.curItem = {}
            this.specssPrice = ""
            this.specss = []
        },
        showSpecs(e) {
            let item = e.currentTarget.dataset.item
            item.count = 1
            item.changeAttribute = []
            this.curItem = item
            this.modalName = "specs"

            console.log(item);

        },
        changeAttribute(item) {
            // 单选 
          
            if (this.curItem.changeAttribute[0] == item) {
                this.curItem.changeAttribute = [
                    
                ]
           }else{
                this.curItem.changeAttribute = [
                    item
                ]
           }


            return false
            // 多选 

            let attr = this.curItem.changeAttribute || []
            // =item、
            let a = attr.find(res => res == item)
            console.log(a);
            if (a) {
                attr = attr.filter(res => res != item)
            } else {
                attr = [
                    ...attr,
                    item
                ]

            }
            this.curItem.changeAttribute = attr

            this.$forceUpdate()
        },
        changeSpecs(item) {
            console.log(item);
            this.curItem.changeSpecs = item.type
            this.curItem.price = item.price
            this.curItem.item = item
            this.$forceUpdate()

        },
        new_jia(e) {

            let item = e.currentTarget.dataset.items
            // ||e.currentTarget.dataset.items
            let index = e.currentTarget.dataset.indexs
            // ||e.currentTarget.dataset.indexs
            if (Object.keys(item).length == 17) {
                this.add(e)
            } else {
                try {
                    if (item.attribute.name || item.specs.name) {
                        if (!item.changeSpecs) {
                            this.tips.tips("请选择" + item.specs.name)
                            return false
                        }
                        if (Number.isInteger(index)) {
                            this.cart[index].count += 1
                            this.totalMoney = (parseFloat(this.totalMoney) + parseFloat(this.cart[index].price * 1)).toFixed(2);
                        } else {
                            this.curItem.count += 1
                        }
                    } else {
                        this.add(e)
                    }
                } catch (error) {
                    // console.log(item);
                    // console.log(error);

                    if (Number.isInteger(index)) {
                        this.cart[index].count += 1
                        this.totalMoney = (parseFloat(this.totalMoney) + parseFloat(this.cart[index].price * 1)).toFixed(2);
                    } else {
                        this.curItem.count += 1
                    }
                    // this.cart[index].count+=1
                    // this.totalMoney =(parseFloat(this.totalMoney)+ parseFloat(this.cart[index].price*1)).toFixed(2);
                    // this.add(e)

                }
            }

        },
        new_jian(e) {
            let item = e.target.dataset.items
            let index = e.target.dataset.indexs

            console.log(Object.keys(item).length);
            // console.log(item.length);
            if (Object.keys(item).length == 17) {
                this.reduce(e)
            } else {

                try {
                    if (item.attribute.name || item.specs.name) {
                        if (Number.isInteger(index)) {
                            this.totalMoney = (parseFloat(this.totalMoney) - parseFloat(this.cart[index].price * 1)).toFixed(2);
                            if (this.cart[index].count > 1) {
                                this.cart[index].count -= 1
                            } else {
                                this.cart.splice(index, 1)
                            }
                        } else {
                            this.curItem.count -= 1
                        }

                    } else {
                        this.reduce(e)
                    }
                } catch (error) {
                    if (Number.isInteger(index)) {
                        this.totalMoney = (parseFloat(this.totalMoney) - parseFloat(this.cart[index].price * 1)).toFixed(2);
                        if (this.cart[index].count > 1) {
                            this.cart[index].count -= 1
                        } else {
                            this.cart.splice(index, 1)
                        }
                    } else {
                        this.curItem.count -= 1
                    }

                }

            }


        },
        selectFood(e) {
            console.log('ji', e.target);
            this.setData({
                activeIndex: e.target.dataset.index,
                viewTo: e.target.dataset.titleid
            });
        },

        calculateHeight() {
            let heigthArr = [];
            let height = 0;
            heigthArr.push(height);
            var query = uni.createSelectorQuery();
            query.selectAll('.title-group').boundingClientRect();
            query.exec((res) => {
                for (let i = 0; i < res[0].length; i++) {
                    console.log(res[0][i]);
                    height += parseInt(res[0][i].height);
                    heigthArr.push(height);
                }

                this.setData({
                    heigthArr: heigthArr
                });
            });
        },

        // 手机端有延迟 节流函数效果不好 用防抖函数凑合
        scroll(e) {
            clearTimeout(timer);
            timer = setTimeout(() => {
                let srollTop = e.detail.scrollTop;

                for (let i = 0; i < this.heigthArr.length; i++) {
                    if (srollTop >= this.heigthArr[i] && srollTop < this.heigthArr[i + 1] && this.activeIndex != i) {
                        this.setData({
                            activeIndex: i
                        });

                        if (i < 3) {
                            this.setData({
                                viewToLeft: 'title1left'
                            });
                        } else {
                            this.setData({
                                viewToLeft: 'title' + (i - 2) + 'left'
                            });
                        }

                        return;
                    }
                }
            }, 100);
        },

        add(e) {
            let groupindex = e.target.dataset.groupindex;
            let index = e.target.dataset.index;
            let countMsg = 'food[' + groupindex + '].items[' + index + '].count';
            let count = this.food[groupindex].items[index].count;
            let foodCountMsg = 'food[' + groupindex + '].foodCount';
            let foodCount = this.food[groupindex].foodCount;
            let foodId = this.food[groupindex].items[index].foodId;
            count += 1;
            foodCount += 1;
            this.food[groupindex].foodCount = foodCount;
            this.food[groupindex].items[index].count = count;
            let cart = this.cart;
            console.log('购物车', cart);
            let hasCart = false;
            var object = {};
            var result = this.result;

            for (var i = 0; i < cart.length; i++) {
                if (cart[i].foodId == foodId) {
                    hasCart = true;
                    break;
                }
            }

            if (hasCart) {
                cart[i].count++;
                result[i].nums++;
            } else {
                cart.push({ ...this.food[groupindex].items[index], groupindex, index });
                object.ids = this.food[groupindex].items[index].id;
                object.nums = this.food[groupindex].items[index].count;
                result.push(object);
            }

            let totalMoney = this.totalMoney;
            totalMoney = parseFloat(totalMoney) + parseFloat(this.food[groupindex].items[index].price);
            totalMoney = totalMoney.toFixed(2);
            console.log('商品', cart); // console.log("总额", totalMoney)
            // console.log("价格", this.data.food[groupindex].items[index].price);
            // console.log("单个商品", this.data.food[groupindex].items[index])
            // if (list[i].num > 0) {
            // }

            console.log(result);
            this.setData({
                cart: cart,
                totalMoney: totalMoney
            });
        },

        reduce(e) {
            console.log("减");
            console.log(e);
            let groupindex = e.target.dataset.groupindex;
            let index = e.target.dataset.index;
            var result = this.result;
            let countMsg = 'food[' + groupindex + '].items[' + index + '].count';
            let count = this.food[groupindex].items[index].count;
            let foodCountMsg = 'food[' + groupindex + '].foodCount';
            let foodCount = this.food[groupindex].foodCount;
            let foodId = this.food[groupindex].items[index].foodId;
            count -= 1;
            foodCount -= 1;
            this.food[groupindex].foodCount = foodCount;
            this.food[groupindex].items[index].count = count;
            let cart = this.cart;

            for (var i = 0; i < cart.length; i++) {
                if (cart[i].foodId == foodId) {
                    console.log(cart[i].count);
                    if (cart[i].count == 1) {
                        cart.splice(i, 1);
                        result.splice(i, 1);
                    } else {
                        cart[i].count--;
                        result[i].nums--;
                    }

                    break;
                }
            }

            if (cart.length == 0) {
                this.setData({
                    showCart: false
                });
            }

            let totalMoney = this.totalMoney;
            totalMoney = (totalMoney - this.food[groupindex].items[index].price).toFixed(2);
            this.setData({
                cart: cart,
                totalMoney: totalMoney
            });
        },

        async check() {
            await this.login().then((res) => {
                console.log("您已登陆！");
            })
            console.log(JSON.stringify(this.cart));
            if ((Number(this.totalMoney) < Number(this.starting_fee)) || this.cart.length < 0) {
                uni.showToast({
                    title: '未满起送费',
                    icon: 'none'
                })
                return false
            }
            var that = this;
            let result = []
            for (let i = 0; i < this.cart.length; i++) {
                const element = this.cart[i];
                let attribute = element.changeAttribute || []
                result = [
                    ...result,
                    {
                        attribute: attribute.join(","),
                        nums: element.count,
                        specs: element.changeSpecs || "",
                        ids: element.id,
                        specss:element.specss,
                        specssPrice:element.specssPrice
                    }
                ]

            }
            // console.log(result);
            // console.log(that.result);
            uni.setStorageSync('json', result);
            uni.setStorageSync('cart', this.cart);
            // uni.setStorageSync('json', that.result);
            // &timeslot=' + this.store.timeslot +'
            uni.setStorageSync('timeslot', this.store.timeslot)
            uni.navigateTo({
                url: '/gc_school/pages/public/index?type=3&id=' + this.store.business_id + "&storeType=" + (this.store.type == 1 ? 0 : 1) + "&is_self_lifting_open=" + this.store.is_self_lifting_open 
            })
            // uni.navigateBack({
            //     delta: 2
            // });
            console.log('结算商品', that.result);
        },

        listCart() {
            if (this.cart.length > 0) {
                this.setData({
                    showCart: !this.showCart
                });
            }
        },

        selectTabItem(e) {
            if (e.target.dataset.index) {
                this.setData({
                    tabIndex: e.target.dataset.index
                });
            }
        },

        preventScrollSwiper() {
            return false;
        },

        showStoreDetail() {
            this.setData({
                showModal: true
            });
        },

        closeModal(e) {
            this.setData({
                showModal: false
            });
        }
    }
};
</script>
<style lang="scss">
page {
    background-color: #fff;
}

.notData {
    display: flex;
    align-items: center;
    flex-direction: column;
    height: 100%;
    justify-content: center;

    .icon {
        width: 80%;
        filter: grayscale(100);
    }
}


.head {
    height: 0rpx;
    /* background: #333; */
    color: #fff;
    display: flex;
}

.head .head-img {
    width: 200rpx;
}

.head .head-img image {
    margin: 18rpx;
    width: 160rpx;
    height: 160rpx;
    border-radius: 20rpx;
}

.head .head-detail {
    flex-grow: 1;
    font-size: 26rpx;
}

.head .head-detail .info {
    height: 60rpx;
    line-height: 60rpx;
}

.head .head-detail .info text {
    border-right: 1rpx solid #eee;
    padding: 0 10rpx;
}

.head .head-detail .info text:last-child {
    border: none;
}

.head .head-detail .publicMsg {
    width: 500rpx;
    height: 60rpx;
    line-height: 60rpx;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
}

.head .actives {
    height: 60rpx;
}

.head .item {
    width: 500rpx;
    height: 60rpx;
    line-height: 60rpx;
    display: flex;
    flex-wrap: wrap;
}

.head .active-icon {
    width: 40rpx;
    height: 40rpx;
    line-height: 40rpx;
    margin-top: 10rpx;
    color: #fff;
    text-align: center;
    margin-right: 10rpx;
}

.head .active-text {
    width: 450rpx;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
}

.manjian {
    background-color: #ff8dc1;
}

.xindian {
    background-color: #75fb6d;
}

.zhekou {
    background-color: #ff111a;
}

.daijinquan {
    background-color: #fbd305;
}

.xinyonghu {
    background-color: #f93fe9;
}

.peisong {
    background-color: #67e1ef;
}

.lingdaijin {
    background-color: #56fb43;
}

.zengsong {
    background-color: #fd86ed;
}

.tab {
    height: 8rpx;
    border-bottom: 2rpx solid #eee;
    display: flex;
    position: relative;
}

.tab .tab-item {
    width: 160rpx;
    line-height: 78rpx;
    text-align: center;
}

.tab .border {
    position: absolute;
    width: 100rpx;
    height: 4rpx;
    background-color: #ffd161;
    top: 76rpx;
    left: 30rpx;
    transition: all 0.5s;
}

.food {
    display: flex;
    height: 100%;
    border-top: 1px solid #eee;
}

.food-class {
    background-color: #f5f9fc;
    /* background-color: #eee; */
    width: 180rpx;
}

.food-class .active {
    background-color: #fff;
}

.food-class .food-class-item {
    position: relative;
    height: 100rpx;
    box-sizing: border-box;
    padding: 10rpx 20rpx;
    font-size: 28rpx;
    line-height: 40rpx;
    display: flex;
    justify-content: center;
    align-items: center;
    width: 180rpx;
}

.food-class .food-class-item:last-child {
    margin-bottom: 120rpx;
}

.food-class .food-class-item .text {
    text-align: center;
    max-height: 80rpx;
    overflow: hidden;
}

.food-class .food-class-item .dot {
    position: absolute;
    width: 30rpx;
    height: 30rpx;
    text-align: center;
    line-height: 30rpx;
    background-color: red;
    right: 4rpx;
    top: 4rpx;
    border-radius: 50%;
    color: #fff;
    font-size: 20rpx;
}

.food-detail {
    flex-grow: 1;
    padding: 0 14rpx;
    font-size: 26rpx;
}

.food-detail .title {
    font-weight: 700;
    padding: 0 20rpx;
    margin-bottom: 20rpx;
    // height: 50rpx;
    line-height: 50rpx;
    /* background-color: #eee; */
    // overflow: hidden;
    // white-space: nowrap;
    text-overflow: ellipsis;
    margin-top: 30rpx;
}

.food-detail .title-group {
    padding-bottom: 30rpx;
}

.food-detail .title-group:last-child {
    margin-bottom: 120rpx;
}

::-webkit-scrollbar {
    width: 0;
    height: 0;
    color: transparent;
}

.food-info {
    margin-bottom: 30rpx;
    display: flex;
}

.food-info:last-child {
    margin-bottom: 0;
}

.food-info .img {
    width: 120rpx;
    text-align: center;
}

.food-info .img image {
    width: 100rpx;
    height: 100rpx;
    border-radius: 15rpx;
}

.food-info .info {
    flex-grow: 1;
    margin-left: 10rpx;
}

.info .name {
    font-size: 28rpx;
    /* font-weight: 700; */
}

.info .note {
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
}

.price-count {
    display: flex;
    height: 50rpx;
    line-height: 50rpx;
}

.price-count .price {
    font-size: 30rpx;
    flex-grow: 1;
    color: red;
}

.price-count .count {
    display: flex;
    line-height: 60rpx;
    flex-grow: 1;
    flex-direction: row-reverse;
}

.price-count .count .num {
    line-height: 50rpx;
    font-size: 30rpx;
}

.btns {
    width: 50rpx;
    height: 50rpx;
    border-radius: 50%;
    font-size: 40rpx;
    font-weight: 700;
    color: black;
    text-align: center;
    line-height: 50rpx;
    background-color: #ffd161;
    margin: 0 16rpx;
}

.cart {
    position: fixed;
    bottom: 0;
    width: 100%;
    height: 110rpx;
    line-height: 110rpx;
    background-color: black;
    /* background-color: #333; */
    /* background-color: #17A9EE; */
}

.cart .cart-container {
    display: flex;
    position: relative;
    color: #eee;
}

.cart .del-price-money {
    flex-grow: 1;
    font-size: 28rpx;
    padding-left: 140rpx;
    display: flex;
    flex-direction: column;
}

.cart .del-price-money .money {
    font-size: 36rpx;
    height: 60rpx;
    /* line-height: 60rpx; */
    line-height: 110rpx;
}

.cart .del-price-money .del-price {
    font-size: 24rpx;
    height: 30rpx;
    line-height: 30rpx;
}

.cart .start-del {
    width: 200rpx;
    font-weight: 700;
    font-size: 30rpx;
    text-align: center;
    color: gray;
    /* color: hsla(0,0%,40%,.5); */
    background-image: linear-gradient(-135deg, #fff5ca, #fff2cc);
    /* background-color: #2f2f2f; */
    /* background-color: #17A9EE; */
}

.cart .cart-img {
    position: absolute;
    top: -24rpx;
    left: 20rpx;
    width: 100rpx;
    height: 100rpx;
    border-radius: 50%;
    background-color: #666;
    text-align: center;
    z-index: 9;
}

.cart .cart-img image {
    width: 60rpx;
    height: 60rpx;
    vertical-align: middle;
    margin-bottom: 20rpx;
}

.cart .has-food {
    color: #333;
    background-image: linear-gradient(134deg, #ffde87, #ffc400);
    /* background-color: #ffd161; */
}

.cart .cart-list {
    position: absolute;
    bottom: 110rpx;
    background-color: #fff;
    width: 100%;
}

.cart .cart-list-header {
    height: 60rpx;
    line-height: 60rpx;
    background-color: #eee;
    text-align: right;
    font-size: 28rpx;
    padding: 0 30rpx;
    color: #333;
}

.cart-list-item {
    max-height: 400rpx;
    overflow: scroll;
}

.cart-list-item .item {
    display: flex;
    align-items: center;
    margin: 20rpx 0;
}

.cart-list-item .item .cart-detail {
    flex: 1;
    /* height: 100rpx; */
    line-height: 40rpx;
    text-align: center;
}

.cart-count {
    display: flex;
    align-items: center;
}

.modal {
    position: fixed;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    z-index: 999;
    background-color: rgba(0, 0, 0, 0.8);
    display: flex;
    flex-direction: column;
}

.modal .top {
    flex-grow: 1;
}

.modal .bottom {
    font-size: 28rpx;
    background-color: #fff;
    padding: 30rpx;
}

.modal .modal-active {
    display: flex;
    margin-bottom: 10rpx;
}

.modal .modal-icon {
    height: 40rpx;
    width: 40rpx;
    line-height: 40rpx;
    color: #fff;
    text-align: center;
}

.modal .modal-text {
    margin-left: 10rpx;
}

.modal .info {
    margin-top: 40rpx;
}

.modal .info .title {
    font-size: 40rpx;
    font-weight: 700;
}

.modal .info text {
    border-right: 1rpx solid #eee;
    padding: 0 10rpx;
}

.modal .info text:first-child {
    padding-left: 0;
}

.modal .info text:last-child {
    border: none;
}

.bgmain {
    background-color: #ff6344;
    color: white;
}

.cuIcon-back {
    color: white;
}

.btns {
    width: 50rpx;
    height: 50rpx;
    border-radius: 50%;
    font-size: 40rpx;
    font-weight: 700;
    color: black;
    text-align: center;
    line-height: 50rpx;
    background-color: #ffd161;
    margin: 0 16rpx;
}

.end {
    background: gray;
    color: white;
}

@import "./main.scss";
</style>
